import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import path from 'path';
import {
  Card, Spin, Avatar, Tooltip, Icon, Input, Row,
  Col, Upload, message, Table, Form, Modal, Button
} from 'antd';
import moment from 'moment';

import { RIGHT, COLORS, RIGHTS } from '../../constants/index'; // RIGHT: 1 写 6 审 5 发
import { QINIU_UPLOAD_DOMAIN, QINIU_DOMAIN, REGEXP } from '../../constants';
import { setUserPhone } from '../../services/user';
import { ChangePsd, accountLogout } from '../../services/api';


import styles from './setting.less'

const FormItem = Form.Item;
const confirm = Modal.confirm;
@Form.create()

class Setting extends PureComponent {
  state = {
    currentEidt: '',
    visible: false,
    phone: '',
    count: 0,
    changePsd: false
  };
  componentDidMount() {
    this.props.dispatch({ type: 'qiniucloud/fetchUptoken' });
  }
  handleSubmit = () => {
    this.props.form.validateFields(['phone', 'sms_code'], (errors, values) => {
      if (errors) {
      } else {
        setUserPhone({ sms: values.sms_code, phone: values.phone, _id: this.props.currentUser._id }).then(res => {
          if (res.error) {
            message.error(res.msg)
          } else {
            message.success(res.msg)
            this.props.dispatch({
              type: 'user/fetchCurrent', callback: res => {
                console.log(res)
              }
            })
            this.setState({ visible: false })
          }
        })
      }
    })
  }
  onGetCaptcha = () => {
    this.props.form.validateFields(['phone'], (err, values) => {
      if (!err) {
        this.props.dispatch({
          type: `login/getSmsCode`,
          payload: {
            phone: values.phone
          },
          callback: res => {
            console.log(res)
            if (res.error) {
              message.error(`系统错误：${res.msg}`)
            } else {
            }
          }
        });
        let count = 59;
        this.setState({ count });
        this.interval = setInterval(() => {
          count -= 1;
          this.setState({ count });
          if (count === 0) {
            clearInterval(this.interval);
          }
        }, 1000);
      }
    });
    // console.log('log')
    // this.props.form.validateFields(['phone'], (errors, values) => {
    //   if(errors) {
    //     message.error(errors.phone.errors[0].message)
    //   } else{
    //     this.props.dispatch({
    //       type: 'login/getSmsCode',
    //       payload: {
    //         phone: values.phone
    //       },
    //       callback: res => {
    //         console.log(res)
    //         if(res.error) {
    //           message.error(`系统错误：${res.msg}`)
    //         } else {
    //         }
    //       }
    //     });
    //     let count = 59;
    //     this.setState({ count });
    //     this.interval = setInterval(() => {
    //       if (count === 1) clearInterval(this.interval);
    //         count--;
    //         this.setState({ count });
    //       }, 1000);
    //   }
    // })
  }
  updateUser = () => {

  }
  hanldeChangePsd = (e) => {
    console.log(e)
    this.props.form.validateFields({ force: true },
      async (err, values) => {
        console.log(values)
        if (!err) {
          const result = await ChangePsd(values);
          if (!result.error) {
            this.props.dispatch({
              type: 'login/logout',
              payload: {
                status: false,
              },
              callback: () => {
                this.props.dispatch(routerRedux.push('/user/login'));
              },
            });
          } else {
            // const result1 = await accountLogout()
            // if (!result1.error) {
            //   this.props.dispatch(routerRedux.push('/user/login'));
            // }
            message.error(result.msg)
          }
        }
      }
    )
  }
  makeUploadData = (file) => {
    const { qiniucloud } = this.props;
    const extname = path.extname(file.name);
    return {
      token: qiniucloud.uptoken,
      key: `${file.uid}${extname}`,
    }
  }
  handleChangeAvatar = async ({ file }) => {
    const { dispatch, currentUser } = this.props;
    let self = this
    if (file.response && !file.error) {
      const url = `${QINIU_DOMAIN}/${file.response.key}`;
      dispatch({
        type: 'user/update',
        payload: {
          _id: currentUser._id,
          avatar: url,
        },
        callback: res => {
          message.success(res.msg)
          dispatch({ type: 'user/fetchCurrent' })
        },
      });
    }
  }
  onChane = (val, name) => {
    this.setState({})
  }
  updata = (val, name) => {
    const { dispatch, currentUser } = this.props;
    currentUser[name] =
      dispatch({
        type: 'user/update',
        payload: {
          _id: currentUser._id,
          [name]: val,
        },
        callback: res => {
          message.success(res.msg)
          dispatch({ type: 'user/fetchCurrent' })
        }
      })
  }
  handleCancel = () => {
    this.setState({ visible: false })
    this.setState({ changePsd: false })
  }
  showModal = () => {
    this.setState({ visible: true })
  }
  showChange = () => {
    this.setState({ changePsd: true })
  }
  renderLevel = (currLevel, defaultLevel) => {
    let levelVnode = [];
    let level = 0;
    let temp = defaultLevel;
    while (temp >= 0) {
      let clsName = styles['level-itme'];
      let passCls = styles['level-pass'];
      let currCls = styles['level-curr'];
      if (level < currLevel) {
        clsName = passCls
      } else if (level === currLevel) {
        clsName = currCls
      }
      if (level === defaultLevel) {
        levelVnode.push(
          <span key={level} className={styles['level-itme']}
            style={{ background: level === currLevel ? 'red' : '#fff', color: level === currLevel ? '#fff' : '#9e9e9e' }}>
            P{level} </span>
        )
      } else {
        levelVnode.push(
          <span key={level}>
            <span className={styles['level-itme']} style={{
              background: level === currLevel ? 'red' : '#fff',
              border: level < currLevel ? '1px solid red' : level === currLevel ? 'none' : '1px solid #9e9e9e',
              color: level < currLevel ? 'red' : level === currLevel ? '#fff' : '#9e9e9e'
            }}
            > P{level} </span>
            <p className={styles['line']} style={{ background: level < currLevel ? 'red' : '#9e9e9e' }}></p>
          </span>
        )
      }
      level++;
      temp--;
    }
    return levelVnode;
  }

  render() {
    let count = this.state.count
    const { getFieldDecorator } = this.props.form;
    const { changePsd } = this.state

    let loading = true;
    let {
      rights, avatar, nickname, writer_level,
      name, phone, taobao
    } = this.props.currentUser;

    let { user, } = this.props
    let teamName = this.props.team.name
    loading = false;

    let hasWrite = rights && (rights.indexOf(RIGHT.writer) >= 0);

    const columns = [{
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    }, {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    }, {
      title: '权限',
      dataIndex: 'rights',
      key: 'rights',
      render(val) {
        if (val) {
          const rights = [];
          val.forEach(item => {
            const right = RIGHTS.find(item1 => item1.value === item);
            if (right) rights.push(right.label);
          });
          return rights.join(',');
        }
        return '';
      },
    }, {
      title: '等级',
      dataIndex: 'writer_level',
      key: 'writer_level',
    }, {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'creare_time',
      render: (val) => moment(val).fromNow()
    }, {
      title: '最近登录',
      dataIndex: 'last_login_time',
      key: 'last_login_time',
      render: (val) => moment(val).fromNow()
    }]
    return (
      <div>
        {hasWrite &&
          <Spin spinning={loading}>
            <Card bodyStyle={{ padding: '30px 20px' }} className={styles['setting-header']} bordered={false} >
              <div className={styles['user-avatar']}>
                <Avatar shape="square" size="large" src={avatar} />
                <div className={styles['edit']}>
                  <Upload
                    name="file"
                    listType="text"
                    showUploadList={false}
                    action={QINIU_UPLOAD_DOMAIN}
                    data={this.makeUploadData}
                    onChange={this.handleChangeAvatar}
                    style={{ color: '#40a9ff', cursor: 'pointer' }}
                  >
                    编辑
                  </Upload>
                </div>
              </div>
              <div className={styles['user-info']} >
                <div className={styles['title']}> {nickname} </div>
                <div className={styles['level']}>
                  {this.renderLevel(writer_level, 7)}
                  <span style={{ marginLeft: '15px', cursor: 'pointer', color: '#1890ff' }}
                    onClick={this.showModal}
                  >
                    写作等级
                    <Tooltip title='点击查看明细' arrowPointAtCenter>
                      <Icon type="question-circle-o" style={{ marginLeft: '5px' }} />
                    </Tooltip>
                  </span>
                </div>
                {/* <div className="lable" style={{marginTop: '20px', display: 'inline-block'}}>
                  {this.renderLable(channelAmont)}
                </div> */}
              </div>
            </Card>
          </Spin>
        }

        <Card title="个人信息" bordered={false} style={{ marginTop: 20 }} >
          <Spin spinning={loading}>
            <InputItem tips="姓名" defaultValue={name}
              updata={(val) => this.updata(val, 'name')}
            />
            <InputItem tips="昵称" defaultValue={nickname}
              updata={(val) => this.updata(val, 'nickname')}
            />
            <InputItem tips="手机号" defaultValue={phone} >
              <Button style={{ marginLeft: 20 }} onClick={this.showModal}>更换</Button>
            </InputItem>
            <InputItem tips="淘宝号" defaultValue={taobao.taobao_user_nick}>
              <Button style={{ marginLeft: 20 }} onClick={this.showModal}>更换</Button>
            </InputItem>
            <InputItem tips="所属团队" defaultValue={teamName} />
            <InputItem tips="密码登录" defaultValue={'*********'}>
              <Button style={{ marginLeft: 20 }} onClick={this.showChange}>更换</Button>
            </InputItem>
          </Spin>
        </Card>

        <Card title="账户权限" bordered={false} style={{ marginTop: 20 }} >
          <Table columns={columns} dataSource={this.props.users} rowKey="_id" />
        </Card>



        <Modal title='更换手机号'
          visible={this.state.visible}
          onCancel={this.handleCancel}
          footer={null}
          bodyStyle={{ display: 'flex', justifyContent: 'center', }}
        >
          <Form onSubmit={this.handleSubmit}>
            <FormItem >
              {getFieldDecorator('phone', {
                initialValue: phone,
                rules: [{
                  max: 11,
                  required: true,
                  message: '请输入正确手机号码',
                  pattern: REGEXP.phone,
                }],
              })(
                <Input style={{ width: 210 }} />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('sms_code', {
                rules: [{
                  len: 6,
                  required: true,
                  message: '请输入验证码！',
                  pattern: REGEXP.code
                }],
              })(
                <Input style={{ width: 100, marginTop: 10 }}
                  placeholder="输入验证码"
                />
              )}
              <Button
                disabled={count}
                onClick={this.onGetCaptcha}
                style={{ marginLeft: 10, width: 100 }}
              >
                {count ? `${count} s` : '获取验证码'}
              </Button>
            </FormItem>
            <FormItem style={{ textAlign: 'center' }} >
              <Button type="primary" onClick={this.check} htmlType="submit">
                确认
                </Button>
            </FormItem>
          </Form>
        </Modal>

        <Modal title='更换密码'
          visible={this.state.changePsd}
          onCancel={this.handleCancel}
          footer={null}
          bodyStyle={{ display: 'flex', justifyContent: 'center', }}
        >
          <Form onSubmit={this.hanldeChangePsd}>
            <FormItem >
              {getFieldDecorator('phone', {
                initialValue: phone,
                rules: [{
                  max: 11,
                  required: true,
                  message: '请输入正确手机号码',
                  pattern: REGEXP.phone,
                }],
              })(
                <Input size="large" style={{ width: 210 }} />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('sms_code', {
                rules: [{
                  len: 6,
                  required: true,
                  message: '请输入验证码！',
                  pattern: REGEXP.code
                }],
              })(
                <Input size="large" style={{ width: 100, marginTop: 10 }}
                  placeholder="输入验证码"
                />
              )}
              <Button
                disabled={count}
                size="large"
                onClick={this.onGetCaptcha}
                style={{ marginLeft: 10, width: 100 }}
              >
                {count ? `${count} s` : '获取验证码'}
              </Button>
            </FormItem>
            <FormItem>
              {getFieldDecorator('pwd', {
                rules: [{
                  required: true, message: '请输入密码',
                }],
              })(
                <Input
                  size="large"
                  type="password"
                  placeholder="输入密码"
                />
              )}
            </FormItem>
            <FormItem style={{ textAlign: 'center' }} >
              <Button type="primary" htmlType="submit">
                确认
                </Button>
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

class InputItem extends PureComponent {
  state = {
    isEdit: false,
    value: '',
  }
  toggle = (flag) => {
    if (flag) this.props.updata(this.state.value)
    this.setState({ isEdit: !flag })
  }
  onChange = (e) => {
    let val = e.target.value;
    this.setState({ value: val })
  }
  render() {
    let isEdit = this.state.isEdit
    let { tips, defaultValue, contText, updata } = this.props
    return (
      <div className={styles['input-item']}>
        <label> {this.props.tips}: </label>
        <Input placeholder="Basic usage" style={{ width: 200 }}
          disabled={!isEdit}
          defaultValue={defaultValue}
          onChange={this.onChange}
        />
        {this.props.children ? this.props.children
          : isEdit
            ? <p className={styles['control']} onClick={() => this.toggle(isEdit)}>
              {contText || '修改'}
            </p>
            : <p className={styles['control']} onClick={() => this.toggle(isEdit)}> 保存 </p>
        }
      </div>
    )
  }
}

const mapState = (state) => {
  return {
    users: state.user.users,
    team: state.user.team,
    currentUser: state.user.currentUser,
    qiniucloud: state.qiniucloud,
  }
}

export default connect(mapState)(Setting);
